package com.example.lib_common.widget.nine_pics

import android.content.Context
import android.util.AttributeSet
import android.view.LayoutInflater
import android.view.View
import android.widget.FrameLayout
import android.widget.Toast
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import com.example.lib_common.R
import com.example.lib_common.dp
import com.example.lib_common.utils.ToastUtils

import com.example.lib_common.widget.nine_pics.Image



/**
 * @author yaotianxue
 * @description
 * @date 2025/2/12
 */
class NineGridPicsView : FrameLayout {
    private val mView: View
    private val mRvPic : RecyclerView

    private var mPicsList:List<Image>? = null // 图片集合
//    private val mItemDecoration by lazy{ //分割线
//        SpaceItemDecoration(10)
//    }
private val mItemDecoration by lazy{ //分割线
    //SpaceItemDecoration(space = 5.dp, spanCount = 3, includeEdge = true)
    SpaceItemDecoration(space = 3.dp, spanCount = 3)
}


    constructor(context: Context):this(context,null)
    constructor(context: Context, attrs: AttributeSet?):this(context,attrs,0)
    constructor(context: Context, attrs: AttributeSet?, defStyleAttr: Int):super(context,attrs,defStyleAttr){
        //mView = LayoutInflater.from(context).inflate(R.layout.layout_nine_gird_pics_view,this)
        mView = LayoutInflater.from(context).inflate(R.layout.layout_nine_grid_pics_view,this)
        mRvPic = mView.findViewById(R.id.rv)
    }

    /**
     * 设置图片资源
     */
    fun setPicsList(list:List<Image>){
        this.mPicsList = list
    }

    /**
     * 初始化view,将图片展示在recyclerview中
     */
    fun initView(){
        if(mPicsList.isNullOrEmpty()){
            return
        }
        val hasSize = ! mPicsList!!.any { it.imageHeight == 0 || it.imageWidth == 0 } // 判断图片是否有尺寸
        val columns = if(hasSize && mPicsList!!.size == 1) 1 else  3 //列数3
        val lg = object :GridLayoutManager(context,columns,RecyclerView.VERTICAL,false) {
            override fun canScrollHorizontally(): Boolean { //不能横向滑动
                return false
            }

            override fun canScrollVertically(): Boolean {//不能纵向滑动
                return false
            }
        }
        mRvPic.layoutManager = lg
        //适配器
        val nineAdapter = NinePicsAdapter(mPicsList!!){
            ToastUtils.showLong(context,"点击了第${it+1}张图片")
        }
        mRvPic.adapter = nineAdapter
//        //分割线
//        mRvPic.removeItemDecoration(mItemDecoration)
//        mRvPic.addItemDecoration(mItemDecoration)
        //分割线
        mRvPic.removeItemDecoration(mItemDecoration)
        mRvPic.addItemDecoration(mItemDecoration)

    }

}